package coder.nav.service;

import cn.hutool.core.bean.BeanUtil;
import coder.nav.enums.NavIdeLangEnums;
import coder.nav.mapper.NavPageMapper;
import coder.nav.model.NavPage;
import coder.nav.model.NavTask;
import coder.nav.model.bo.NavIdeRunBO;
import coder.nav.model.bo.NavPageBO;
import coder.nav.model.bo.NavPageQueryBO;
import coder.nav.model.bo.NavTaskQueryBO;
import coder.nav.model.vo.NavCustomVO;
import coder.nav.model.vo.NavIdeRunOutErrVO;
import coder.nav.model.vo.NavPageVO;
import coder.nav.model.vo.NavTaskVO;
import coder.nav.schedule.action.NavTaskDayCashAction;
import coder.nav.utils.JwtUtils;
import coder.nav.utils.MdStyleUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class NavPageService extends ServiceImpl<NavPageMapper, NavPage> {

    @Autowired
    private NavIdeService ideService;

    /**
     * 帮助手册
     */
    public String readme() {
        String url = "https://gitee.com/bosen-once/coder-nav";
        try {
            Document document = Jsoup.connect(url).get();
            String markdown = document.getElementsByClass("markdown-body").get(0).text();
            markdown = markdown.replaceAll("src/main/resources/static", "");
            return MdStyleUtils.markdownToStyledHtml("Coder-nav-帮助手册", markdown);
        } catch (IOException e) {
            return "";
        }
    }

    /**
     * 动态页面
     * @param userId 用户id
     * @param pageUrl 页面地址
     */
    public String page(Long userId, String pageUrl) {
        NavCustomVO page = this.getPageInfoByUrl(userId, pageUrl);
        NavIdeRunBO ideRunBO = new NavIdeRunBO();
        ideRunBO.setLang(NavIdeLangEnums.PHP.getValue());
        ideRunBO.setCode(page.getContext());
        NavIdeRunOutErrVO ideRunOutErrVO = ideService.run(ideRunBO, 1L);
        return ideRunOutErrVO.getContext();
    }

    /**
     * 静态页面
     * @author Bosen 2025/11/9 14:33
     */
    public String share(Long userId, String pageUrl) {
        ClassLoader classLoader = NavTaskDayCashAction.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("static/temp/share.html");
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while(true) {
            try {
                if ((line = br.readLine()) == null) break;
            } catch (IOException ignored) {}
            sb.append(line).append("\n");
        }
        return String.format(sb.toString(), userId, pageUrl);
    }

    /**
     * 保存动态页面
     * @param bo 入参
     */
    public void savePage(NavPageBO bo) {
        NavPage entity = BeanUtil.copyProperties(bo, NavPage.class);
        Long userId = bo.getUserId();
        if(Objects.isNull(userId)) {
            userId = JwtUtils.getUserId();
        }
        entity.setUserId(userId);
        // 页面链接判断
        if(StringUtils.isNotBlank(bo.getUrl())) {
            NavCustomVO exist = getPageInfoByUrl(userId, bo.getUrl());
            if(Objects.nonNull(exist) && !Objects.equals(bo.getId(), exist.getId())) {
                throw new RuntimeException("已存在相同链接页面");
            }
        }
        if(Objects.isNull(entity.getId())) {
            this.baseMapper.insert(entity);
            return;
        }
        this.updateById(entity);
    }

    /**
     * 删除动态页面
     * @param id 主键id
     */
    public void deletePage(Long id) {
        LambdaQueryWrapper<NavPage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavPage::getUserId, JwtUtils.getUserId())
                .eq(NavPage::getId, id);
        this.baseMapper.delete(queryWrapper);
    }

    /**
     * 获取动态页面
     * @param id 主键id
     */
    public NavCustomVO getPageInfo(Long id) {
        LambdaQueryWrapper<NavPage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavPage::getId, id);
        NavPage entity = this.baseMapper.selectOne(queryWrapper);
        return BeanUtil.copyProperties(entity, NavCustomVO.class);
    }

    /**
     * 通过页面链接动态页面
     * @param userId 用户id
     * @param pageUrl 页面链接
     */
    public NavCustomVO getPageInfoByUrl(Long userId, String pageUrl) {
        if(StringUtils.isBlank(pageUrl)) {
            return null;
        }
        LambdaQueryWrapper<NavPage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavPage::getUserId, userId)
                .eq(NavPage::getUrl, pageUrl);
        NavPage entity = this.baseMapper.selectOne(queryWrapper);
        return BeanUtil.copyProperties(entity, NavCustomVO.class);
    }

    /**
     * 动态页面分页
     * @param bo 入参
     */
    public NavPageVO<NavCustomVO> getPage(NavPageQueryBO bo) {
        LambdaQueryWrapper<NavPage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NavPage::getUserId, JwtUtils.getUserId());
        queryWrapper.orderByDesc(NavPage::getSort);
        Page<NavPage> limit = new Page<>(bo.getPageIndex(), bo.getPageSize(), true);
        Page<NavPage> page = this.baseMapper.selectPage(limit, queryWrapper);
        NavPageVO<NavCustomVO> vo = new NavPageVO<>(bo.getPageIndex(), bo.getPageSize(), page.getTotal());
        vo.setData(page.getRecords().stream().map(item -> BeanUtil.copyProperties(item, NavCustomVO.class)).collect(Collectors.toList()));
        return vo;
    }

}
